import wx
import subprocess
from threading import Thread
from icon import geticonIcon
import time
import os
import traceback

########################################################################
class TrayIcon(wx.TaskBarIcon):
	TBMENU_CLOSE   = wx.NewId()
	TBMENU_STATUS   = wx.NewId()

	#----------------------------------------------------------------------
	def __init__(self, app):
		wx.TaskBarIcon.__init__(self)
		
		self.app = app
		
		# Set the image
		self.SetIcon(geticonIcon(), "MyVpn")
 
		# bind some events
		self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE)
 
	#----------------------------------------------------------------------
	def CreatePopupMenu(self, evt=None):
		"""
		This method is called by the base class when it needs to popup
		the menu for the default EVT_RIGHT_DOWN event.  Just create
		the menu how you want it and return it from this function,
		the base class takes care of the rest.
		"""
		menu = wx.Menu()
		if self.app.connecting:
			try:
				with open("bin\\status") as f:
					menu.Append(self.TBMENU_STATUS, f.readline().strip())
			except:
				menu.Append(self.TBMENU_STATUS, "Connecting")
		else:
			menu.Append(self.TBMENU_STATUS, "Not Connected")
		menu.Append(self.TBMENU_CLOSE, "Exit")
		return menu

 
	#----------------------------------------------------------------------
	def OnTaskBarClose(self, evt):
		"""
		Destroy the taskbar icon and frame from the taskbar icon itself
		"""
		self.app.onExit();
 

 
########################################################################
class MyVpnApp():
	def runVpn(self):
		while self.running:
			si = subprocess.STARTUPINFO()
			si.wShowWindow = subprocess.SW_HIDE
			#si.dwFlags = subprocess.STARTF_USESTDHANDLES
			si.dwFlags = subprocess.STARTF_USESHOWWINDOW
			try:
				if os.path.exists("bin\\status"):
					os.remove("bin\\status")
			except:
				pass
			self.p = subprocess.Popen("bin\\MyVpn config.txt", cwd="bin", startupinfo=si)
			self.connecting = True
			self.p.wait()
			self.connecting = False
			if self.running:
				print "MyVpn process exited, restart 3s later"
				time.sleep(3)
	
	#----------------------------------------------------------------------
	def __init__(self):
		self.connecting = False
		self.running = True
		self.tbIcon = TrayIcon(self)
		self.p = None
		Thread(target=self.runVpn).start()
		
 
	#----------------------------------------------------------------------
	def onExit(self):
		"""
		Destroy the taskbar icon and the frame
		"""
		self.running = False;
		try:
			print "Exiting"
			if self.p:
				print "Killing myvpn process, pid: %d" % (self.p.pid)
				self.p.terminate()
			
			try:
				with open("bin\\config.txt", "r") as f:
					dev = [line.strip() for line in f.read().split('\n') if "dev" in line]
					if dev:
						dev = dev[0].split('=', 1)[1].strip()
						si = subprocess.STARTUPINFO()
						si.wShowWindow = subprocess.SW_HIDE
						si.dwFlags = subprocess.STARTF_USESHOWWINDOW
						subprocess.Popen('netsh interface set interface "%s" disabled' % (dev,), startupinfo=si).wait()
			except:
				traceback.print_exc()
		except:
			pass
		self.tbIcon.RemoveIcon()
		self.tbIcon.Destroy()
		
 
#----------------------------------------------------------------------
# Run the program
app = wx.App(False)
vpnApp = MyVpnApp()
app.MainLoop()